package work.timejay.shop.service.sys.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import work.timejay.common.SuperServiceImpl;
import work.timejay.dto.shop.MenuAddDTO;
import work.timejay.dto.shop.MenuPageDTO;
import work.timejay.enums.ErrorMsg;
import work.timejay.exception.TimeJayException;
import work.timejay.shop.entity.sys.SysMenu;
import work.timejay.shop.entity.sys.SysRoleMenu;
import work.timejay.shop.entity.user.User;
import work.timejay.shop.mapper.sys.SysMenuMapper;
import work.timejay.shop.service.sys.SysMenuService;
import work.timejay.shop.service.sys.SysRoleMenuService;
import work.timejay.shop.service.user.UserService;
import work.timejay.utils.LoginHelper;
import work.timejay.vo.shop.MenuItemVO;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author 王文杰
 * @since 2024-02-07
 */
@Service
public class SysMenuServiceImpl extends SuperServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private UserService userService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;


    @Override
    public List<MenuItemVO> menuList(MenuPageDTO dto) {
        JSONObject userJson = LoginHelper.loginUserInfoByJson();
        String userId = userJson.getStr("id");
        if (StringUtils.isEmpty(userId)) {
            throw TimeJayException.fail(ErrorMsg.USER_CACHE_IS_NULL);
        }
        User user = userService.getById(userId);
        if (null == user) {
            throw TimeJayException.fail(ErrorMsg.USER_CACHE_IS_NULL);
        }
        List<SysRoleMenu> sysRoleMenus = sysRoleMenuService.findInfoByRoleId(user.getRoleId());
        if (CollectionUtils.isEmpty(sysRoleMenus)) {
            return new ArrayList<>();
        }
        List<Long> menuIds = sysRoleMenus.stream()
                .map(SysRoleMenu::getMenuId)
                .collect(Collectors.toList());
        List<SysMenu> menuInfos = lambdaQuery()
                .in(SysMenu::getId, menuIds)
                .list();
        if (CollectionUtils.isEmpty(menuInfos)) {
            return new ArrayList<>();
        }
        return BeanUtil.copyToList(menuInfos, MenuItemVO.class);
    }

    @Override
    public void addMenu(MenuAddDTO dto) {
        SysMenu sysMenu = BeanUtil.toBean(dto, SysMenu.class);
        sysMenu.setId(IdWorker.getId());
        baseMapper.insert(sysMenu);
    }

    @Override
    public void updateMenu(MenuAddDTO dto) {
        SysMenu sysMenu = BeanUtil.toBean(dto, SysMenu.class);
        baseMapper.updateById(sysMenu);
    }
}
